import {reqInsorder,reqUpdorder,reqGetorder,prevent,updhot} from '../../api/order'
import {confirmDeduction,reqSelidandtype} from '../../api/inventory'
import {updcountnum} from '../../api/product'

// pages/order/order.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    password:'',
    passwordLength:6,
    usepasstrue:false,
    value: '',
    contactPhone:'',
    contactName:'',
    descriptionShow: false,
    checkedContatesList:[{
      id:0,
      name:'',
      idcard:'',
      phone:''
    }],//填写的常用联系人集合
    linkman:{
      name:'',
      phone:''
    },//填写的联系人信息
    showpay: false,
    ticket:{},
    choose:'',
    year:'',
    bigname:'',
    orderno:'',
    token:'',
    user:{},
    ooo:{}
  },
  usepass(){
    prevent(this.data.orderno).then(aaa=>{
      console.log(aaa)
      if(aaa.msg=='商品被下架'){
        wx.showToast({
          title: '商品已被下架',
          icon:'error'
        })
      }else{
    this.setData({
      usepasstrue:true,
      showpay:false
    })
  }
})
  },

  // 点击密码容器时，让隐藏的输入框获取焦点，弹出键盘
  focusInput() {
    // 获取输入框组件并使其聚焦
    const input = this.selectComponent('#passwordInput');
    if (input) {
      input.focus();
    }
  },

  // 处理输入事件，更新密码
  handleInput(e) {
    this.setData({
      password: e.detail.value
    });
    if (e.detail.value.length === this.data.passwordLength) {
      const input = this.selectComponent('#passwordInput');
      input && input.blur();
      this.setData({ usepasstrue: false });
    reqUpdorder(1,this.data.orderno) 
    .then(response => {
      if (response === "修改成功") {
        console.log("修改成功")
        updcountnum(this.data.ticket.productId,this.data.ticket.productType);
        reqSelidandtype(this.data.ticket.id).then(res=>{  
          console.log(res)
          let yeartoday=this.data.year+"-"+this.data.choose;
          confirmDeduction(res.productId,res.productType,yeartoday,this.data.ticket.num);
      
          //判断是不是类型
          if(res.productType==1){
           updhot();
          }
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/mine/ewm/ewm?ooo='+encodeURIComponent(JSON.stringify(this.data.ooo))
          })
        }, 1000);
      } else {
        console.error("订单状态更新失败");
      }
    })
    .catch(error => {
      console.error("请求失败", error);
    });

      console.log('输入的密码：', e.detail.value);
    }
  },

onClickShow() {

  const uniqueContactsIds = [...new Set(this.data.checkedContatesList.map(item => item.id))];
  const hasValidContacts = uniqueContactsIds.length > 0 && 
  !uniqueContactsIds.includes(0);

// 再判断联系人名称是否有效（非null且非空）
const hasValidName = this.data.linkman?.name != null && 
this.data.linkman.name.trim() !== '';

// 最终条件：两个都满足才通过
if (hasValidContacts && hasValidName) {
  // 集中组装 order，确保数据准确
  const order = {
    userId: this.data.user.userId,
    detailId: this.data.ticket.id,
    quantity: this.data.ticket.num,
    totalAmount: this.data.ticket.total,
    contactsId: uniqueContactsIds.join(","),
    tourdate: this.data.year+"-"+this.data.choose+" "+this.data.ticket.playtime
  };

    reqInsorder(order).then(res => {
      if(res.message=='套餐已被下架'){
        this.setData({'showpay':false})
        wx.showToast({
          title: '商品已被下架',
          icon:'error'
        })
      }else{
      // 请求成功处理
      this.setData({
        orderno:res.data.orderno,
        showpay: true
      })
      reqGetorder(res.data.orderno).then(result=>{
        this.setData({
          ooo:result.data.one
        })
      })
      console.log("res:"+res)
    }
    }).catch(err => {
      // 请求失败处理
      console.error('请求出错：', err);
    });
  

  }else{
    wx.showToast({
      title: '请填写完整信息',
      icon:'error'
    })
  }
},

onClickHide() {
  this.setData({ showpay: false });
},

  showDescription(){
    this.setData({
      descriptionShow:!this.data.descriptionShow
    })
  },
  showContactInfo(e){
    console.log(e)
    //先存住当前填写的联系人信息
    wx.setStorageSync('linkman', this.data.linkman)
    let type=e.currentTarget.dataset.type
    let rule=e.currentTarget.dataset.rule
    //计算被填写的空格
    let fullnum=[]
    if(type==0){
      fullnum=this.data.checkedContatesList.filter((item)=>{
        return item.name !='' || item.idcard !=''
      })
    }
    let minpeople=e.currentTarget.dataset.minpeople
    let maxNum=1
    if (minpeople!=null && minpeople!='') {
           maxNum=e.currentTarget.dataset.maxnum * minpeople-fullnum.length
    }else{
      console.log("?????????????????")
      maxNum=e.currentTarget.dataset.maxnum-fullnum.length
    }
    wx.setStorageSync('checkedContatesList', this.data.checkedContatesList)
    wx.setStorageSync('linkman', this.data.linkman)
    wx.navigateTo({
      url: '/pages/adduser/mineucontates/mineucontates?maxnum='+maxNum+"&type="+type+"&rule="+rule,
    })
    
  },
  
  close(){
    this.setData({
      show:false
    })
  },
  //修改游玩人姓名
  onNameChange(e){
    const index=e.currentTarget.dataset.index
    const list=[...this.data.checkedContatesList]
    if(list.length<index+1){
      list.push({'name':e.detail,'idcard':''})
    }else{
      list[index].name=e.detail
    }
    this.setData({
      checkedContatesList:list
    })
  },
  //修改游玩人身份证
  onIdcardChange(e){
    const index=e.currentTarget.dataset.index
    const list=[...this.data.checkedContatesList]
    if(list.length<index+1){
      list.push({'name':'','idcard':e.detail})
    }else{
      list[index].idcard=e.detail
    }
    this.setData({
      checkedContatesList:list
    })
  },
  //修改联系人姓名
  linkNameChange(e){
    this.setData({
      'linkman.name':e.detail
    })
    console.log(this.data.linkman)
  },
  //修改联系人电话
  linkPhoneChange(e){
    this.setData({
      'linkman.phone':e.detail
    })
  },
  onusers(){
    const userInfo=wx.getStorageSync('userInfo');
    const token=wx.getStorageSync('token')
    if(token!=null){
      this.setData({
        user:userInfo,
        token
      })
    }
  },

onShow(){

},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.onusers();
    wx.setStorageSync('zhi', options)
    // let list=wx.getStorageSync('checkedContatesList')
    // console.log(list)
    // let linkman=wx.getStorageSync('linkman')
    // console.log(linkman)
    // this.setData({
    //   linkman:linkman==''?this.data.linkman:linkman,
    //   checkedContatesList:list.length==0?this.data.checkedContatesList:list
    // })
    wx.getStorageSync('zhi')
    const options2 = wx.getStorageSync('zhi');
    if (options2) {
      console.log(options2);
       const ticket = JSON.parse(decodeURIComponent(options2.ticket));
       console.log(ticket)
       const choose = options2.choose;
       const year=options2.year;
       const bigname=options2.bigname;
      this.setData({
        ticket,
        choose:choose.replace('.','-'),
        year,
        bigname
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //清除缓存
    wx.removeStorageSync('checkedContatesList')
    wx.removeStorageSync('linkman')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})